package br.com.vagacerta.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import br.com.vagacerta.modelo.Sensor;

@Repository
public class SensorDAO {

	private Connection connection;

	@Autowired
	public SensorDAO(DataSource dataSource) {
		try {
			this.connection = dataSource.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public Sensor retornaSensorPorId(long idSensor) {

		try {

			String sql = "SELECT * FROM SENSOR WHERE COD_SENSOR = ?";

			PreparedStatement stmt;
			stmt = connection.prepareStatement(sql);

			stmt.setLong(1, idSensor);
			ResultSet rs = stmt.executeQuery();
			Sensor sensor = new Sensor();

			while (rs.next()) {

				sensor.setCodigoSensor(rs.getLong("COD_SENSOR"));
				sensor.setNomeSensor(rs.getString("NOME_SENSOR"));
				sensor.setStatusSensor(rs.getShort("STATUS_SENSOR"));

			}

			rs.close();
			stmt.close();

			return sensor;

		} catch (SQLException e) {
			throw new RuntimeException(e);

		}

	}

	public Sensor carregaSensorPorNome(String nomeSensor) {
		try {
		String sql = "SELECT * FROM SENSOR WHERE NOME_SENSOR = ? LIMIT 1";

		PreparedStatement stmt;
		stmt = connection.prepareStatement(sql);

		stmt.setString(1, nomeSensor);
		ResultSet rs = stmt.executeQuery();
		Sensor sensor = new Sensor();

		while (rs.next()) {

			sensor.setCodigoSensor(rs.getLong("COD_SENSOR"));
			sensor.setNomeSensor(rs.getString("NOME_SENSOR"));
			sensor.setStatusSensor(rs.getShort("STATUS_SENSOR"));

		}

		rs.close();
		stmt.close();

		return sensor;

		} catch (SQLException e) {
			throw new RuntimeException(e);

		}
	}
	
	
}